package lt.vin.exaatto.server;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.google.appengine.api.xmpp.JID;

public class ParsedJid {
		
		private final String node;
		
		private final String domain;
		
		private final String resource;
		
		private final JID jid;
		
		public static ParsedJid parse(JID jid) {
			Pattern pattern = Pattern.compile("(.+?)@([^/]+)/?(.*)");
			Matcher matcher = pattern.matcher(jid.getId());
			if (matcher.matches()) {
				return new ParsedJid(
						matcher.group(1), 
						matcher.group(2), 
						matcher.group(3),
						jid);
			} else {
				return null;
			}
		}
		
		private ParsedJid(String node, String domain, String resource, JID jid) {
			this.node = node;
			this.domain = domain;
			this.resource = StringUtils.defaultIfEmpty(resource, null);
			this.jid = jid;
		}

		/**
		 * @return the node
		 */
		public String getNode() {
			return node;
		}

		/**
		 * @return the domain
		 */
		public String getDomain() {
			return domain;
		}

		/**
		 * @return the resource
		 */
		public String getResource() {
			return resource;
		}

		/**
		 * @return the jid
		 */
		public JID getJid() {
			return jid;
		}
		
		public String getAddress() {
			return getNode() + "@" + getDomain();
		}
	}